<?php

namespace App\Http\Controllers\Home;

use App\Helpers\Helpers;
use App\Model\Express;
use App\Model\Order;
use App\Model\UserCoupon;
use App\Model\WeChatFromId;
use App\Model\WeChatNotify;
use App\Model\WineProduct;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Validation\Rule;

class OrderController extends BaseController
{

    public function index(Request $request)
    {
        $state = $request->input('state');
        $user = $this->loginUser();

        $query = Order::with([
            'product' => function($q){
                $q->select('id','name','chname','price','vintage','banner');
            },
            'createUser'  =>  function($q){
                $q->select('id','name','avatar');
            },
            'getUser'  =>  function($q){
                $q->select('id','name','avatar');
            }
        ]);
        $query = $query->whereRaw('(orders.create_user_id='.$user->id.' or orders.get_user_id='.$user->id.')');

        $arr = ['paying'=>0,'delivering'=>1,'cancel'=>2,'unclaimed'=>3,'expired'=>4,'receiving'=>5,'complete'=>6,'close'=>7,
            'pending'=>8,'refunding'=>9,'refunded'=>10];

        if (isset($arr[$state])) {
            $query = $query->where('state','=',$arr[$state]);
        }

        $items = $query->where('user_del','=',0)->orderBy('created_at','desc')->get();

        foreach ($items as $key => $order) {
            if ($order->state==3 && $order->expire_time && strtotime($order->expire_time) < time()){
                $order->state = 4;
                $order->save();
            }

        }

        return $this->success($items);
    }

    //创建订单
    public function store(Request $request)
    {
        //购买用户
        $user = $this->loginUser();

        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        //验证规则
        $rules = [
            'type' =>'required|in:general,gift',
            'origin' =>'required|in:general,qrcode',
            'origin_qrcode'=>'required_if:type,qrcode',
            'product_id' =>[
                'required',
                'numeric',
                Rule::exists('wine_product','id')->whereNull('deleted_at')->where('sell_method','online')
            ],
            'quantity' => 'required|numeric|min:1',
            'address_id' => [
                'required_if:type,general',
                'numeric',
                Rule::exists('t_user_addresses','id')->where(function($query) use($user){
                    $query->where('user_id',$user->id);
                })
            ],
        ];

        //验证消息
        $message = [
            'product_id.exists' => '商品不存在或已下架',
            'address_id.exists' => '地址不存在'
        ];

        //验证请求
        if(!$this->requestValidate($request->all(),$rules,$message)){
            return $this->failed($this->error);
        }

        $product = WineProduct::find($request->input('product_id'));
        $d = $request->only('type','product_id','quantity');

        //判断商品是否已下线
        if ($product->online != "yes"){
            return $this->failed('商品已下线');
        }

        //判断商品库存
        if ($product->sku < $d['quantity']) {
            return $this->failed('库存不足');
        }

        //减库存sku
        $product->sku -= $d['quantity'];
        $product->save();

        //订单金额信息
        //商品未促销价格
        $d['origin_price']  = $product->price;
        //商品促销价格
        $d['price']  = $product->promotion_price==0?$product->price:$product->promotion_price;
        //商品未促销总金额
        $d['origin_product_total_fee'] =  $d['origin_price']*$d['quantity'];
        //商品促销总金额
        $d['product_total_fee'] =  $d['price']*$d['quantity'];
        //运费
        $d['deliver_fee'] = 0;

        $coupon = false;
        //优惠券
        if ($coupon_id = $request->input('coupon_id')){
            $coupon = UserCoupon::find($coupon_id);
            if (!$coupon) return $this->failed('优惠券不存在');
            //检测用户是否可以使用优惠券
            $res = UserCoupon::checkCanUse($coupon,$user,$d['product_total_fee'] + $d['deliver_fee'],$d['product_id']);
            if (!$res['success']){
                return $this->failed($res['error']);
            }
            //$d['coupon_id'] = $coupon_id;
            $d['coupon_name'] = $coupon->coupon->name;
            $d['coupon_fee'] = $coupon->coupon->category->amount;
        }

        //订单其他信息
        $d['address_id'] = $request->input('address_id',0);
        $d['comment'] = $request->input('comment','');
        $d['origin'] = $request->input('origin','general');
        $d['origin_qrcode'] = $request->input('origin_qrcode','');

        $d['product_name'] = $product->name;
        $d['product_chname'] = $product->chname;

        //添加一个进口商
        if ($importer = $product->relationImporters()->first()) {
            $d['importer_id'] = $importer->id;
            $d['importer_name'] = $importer->name;
        }

        //创建订单
        $m = new Order();
        $m->out_trade_no = Helpers::createOrderOutTradeNo($d['type']);
        $m->md5_out_trade_no = md5($m->out_trade_no);
        $m->create_user_id = $user->id;
        $m->fill($d);
        //待支付
        $m->state = 0;
        //是否已支付
        $m->is_pay = "no";
        //是否已发货
        $m->is_delivery = "no";
        //订单总金额(包含运费)
        $m->total_fee = $m->product_total_fee + $m->deliver_fee - $m->coupon_fee;
        if ($d['type'] == "gift") {
            $expire = Config::get('order.order_expire_time');
            $m->expire_time = date('Y-m-d H:i:s',time() + $expire);
        }
        $m->save();

        //更新订单量统计
        $user->updateOrderCount();

        if ($coupon) {
            $coupon->order_id = $m->id;
            $coupon->used_at = Helpers::now();
            $coupon->state = 1;
            $coupon->save();

            //更新优惠券使用统计
            $coupon->updateCouponCount();
        }

        //添加收件信息
        if ($d['type'] == "general") {
            $m->addAddressInfo($m->address_id,$user->id);
        }

        return $this->success($m);
    }

    //详细
    public function show($id)
    {
        $user = $this->loginUser();

        $order = Order::find($id);

        if (!$order) return $this->notFond();

        if ($order->type == 'generate' && !($order->create_user_id == $user->id || $order->get_user_id == $user->id)) {
            return $this->notFond();
        }

        if ($order->state == 3 && $order->expire_time && strtotime($order->expire_time) < time()){
            $order->state = 4;
            $order->save();
        }

        $order->load('payRecord','product','product.covers','createUser','getUser','qrcodeRecord','product.userHasDrink',
            'product.userWantDrink',"product.wineGrading","product.scenes",'product.drinkTasteKeywords',
            'product.cuisines','product.wineTastes');

        return $this->success($order);
    }

    //赠送礼物给朋友
    public function giftOfGive(Request $request)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $user = $this->loginUser();

        $rules = [
            'blessing' =>'required',
            'id' => [
                'required',
                Rule::exists('orders','id')->where(function($query) use($user){
                    $query->whereIn('state',[3,4])->where('type','gift')->where('create_user_id',$user->id);
                })
            ],
        ];

        if(!$this->requestValidate($request->all(),$rules)){
            return $this->failed($this->error);
        }

        $blessing = $request->input('blessing');
        $id = $request->input('id');

        $order = Order::find($id);

        $order->blessing = $blessing;
        $order->state = 3;
        $order->save();
        return $this->message('success');

        //$url = Order::createGiftCompleteUrl($order,time());

        //return $this->success(['urlParam'=>$url]);
    }

    //显示礼物界面
    public function giftOfShow(Request $request)
    {
        $rules = [
            'giftCode' => [
                'required',
                Rule::exists('orders','md5_out_trade_no')->where(function($query){
                    $query->where('type','gift')->where('is_pay','yes');
                })
            ],
            'timestamp' => 'required',
            'signCode' => 'required'
        ];

        if(!$this->requestValidate($request->all(),$rules)){
            return $this->failed($this->error);
        }

        $md5_out_trade_no = $request->input('giftCode');
        $timestamp = $request->input('timestamp');
        $signCode = $request->input('signCode');
        $order = Order::where('md5_out_trade_no','=',$md5_out_trade_no)->first();

        if ($order->state == 3 && $order->expire_time && strtotime($order->expire_time) < time()){
            $order->state = 4;
            $order->save();
        }

        if(!Order::checkGiftUrlParam($order,$timestamp,$signCode)){
            return $this->failed('invalid');
        }

        $order->load('payRecord','product','product.covers','createUser','getUser','qrcodeRecord',
            'product.userHasDrink','product.userWantDrink',"product.wineGrading","product.scenes",'product.drinkTasteKeywords',
            'product.cuisines','product.wineTastes');

        return $this->success($order);
    }

    //领取礼物
    public function giftOfGet(Request $request)
    {
        $user = $this->loginUser();

        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$user->weixinId);
        }

        $rules = [
            'giftCode' => [
                'required',
                Rule::exists('orders','md5_out_trade_no')->where(function($query){
                    $query->where('state',3)->where('type','gift')->where('is_pay','yes');
                })
            ],
            'timestamp' => 'required',
            'signCode' => 'required',
            'address_id' =>  Rule::exists('t_user_addresses','id')->where(function($query) use($user){
                $query->where('user_id',$user->id);
            })
        ];

        if(!$this->requestValidate($request->all(),$rules)){
            return $this->failed($this->error);
        }

        $md5_out_trade_no = $request->input('giftCode');
        $timestamp = $request->input('timestamp');
        $signCode = $request->input('signCode');
        $order = Order::where('md5_out_trade_no','=',$md5_out_trade_no)->first();

        if ($order->state == 3 && $order->expire_time && strtotime($order->expire_time) < time()){
            $order->state = 4;
            $order->save();
            return $this->failed('已过期');
        }

        if(!Order::checkGiftUrlParam($order,$timestamp,$signCode)){
            return $this->failed('invalid');
        }

        $order->get_user_id = $user->id;
        $order->get_time = date('Y-m-d H:i:s');
        $order->addAddressInfo($request->input('address_id'),$user->id);
        $order->state = 1;
        $order->save();

        $wn = new WeChatNotify();
        $wn->giftReceived($order);

        return $this->success($order);

    }

    //重新赠送
    public function giftOfResend(Request $request,$id)
    {
        $user = $this->loginUser();

        $order = Order::where('create_user_id','=',$user->id)->find($id);

        if ($order) {
            if (in_array($order->state,[3])){
                if ($blessing = $request->input('blessing')) {
                    $order->blessing = $blessing;
                }
                $expire = Config::get('order.order_expire_time');
                $order->expire_time = date('Y-m-d H:i:s',time() + $expire);
                $order->state = 3;
                $order->save();

                $url = Order::createGiftCompleteUrl($order,time());
                return $this->success(['urlParam'=>$url]);
            }
            return $this->failed('invalid');

        }
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }
        return $this->notFond();
    }

    //确认收货
    public function complete(Request $request,$id)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $user = $this->loginUser();
        $order = Order::where('get_user_id','=',$user->id)->find($id);

        if (!$order) return $this->notFond();

        if ($order->state == 5) {
            $order->state = 6;
            $order->finish_time = date('Y-m-d H:i:s');
            $order->save();

            //更新订单量统计
            User::updateOrderCountByUserId($order->create_user_id);


            //发送确认收货成功模板消息
            $m = new WeChatNotify();
            $m->confirmReceipt($order);

            return $this->message('success');
        }
        return $this->failed('fail');
    }

    //物流
    public function express($id)
    {
        $user = $this->loginUser();

        //$order = Order::where('get_user_id','=',$user->id)->find($id);
        $order = Order::find($id);

        if (!$order) return $this->notFond();

        if($order->express) $order->express->updateTrackingRealTime();

        $order->load(['product','product.covers','express','express.carrier']);

        return $this->success($order);
    }

    //删除订单记录
    public function delete(Request $request,$id)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $order = Order::find($id);

        if (!$order) return $this->notFond();

        $can = [0,2,4,6,7,8,10];

        if (!in_array($order->state,$can)){
            return $this->failed('不能删除');
        }

        $order->user_del = 1;
        $order->user_del_time = Helpers::now();

        if ($order->state == 0) {
            $order->state == 2;
        }
        
        $order->save();

        //订单回库
        Order::skuReturnBySinge($order);

        return $this->message('success');
    }

    //取消订单
    public function cancel(Request $request,$id)
    {
        if ($formid = $request->input('formid')){
            WeChatFromId::createFromForm($formid,$this->loginUser()->weixinId);
        }

        $order = Order::find($id);

        if (!$order) return $this->notFond();

        $can = [0];

        if (!in_array($order->state,$can)){
            return $this->failed('只能取消待支付订单');
        }

        $order->state = 2;
        $order->save();

        //订单回库
        Order::skuReturnBySinge($order);

        return $this->message('success');
    }
}
